package com.bug.mamage;

import com.bug.BugProcessor;
import com.bug.CatchStrategy;
import com.bug.downloader.MyHttpClientDownloader;
import com.model.WordInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import us.codecraft.webmagic.Spider;

import java.util.concurrent.*;

@Slf4j
public class WordInfoManage {


    // 当前策略
    private final CatchStrategy CATCH_STRATEGY = null;
    private final int THREAD_COUNT = 2;
    private final CatchStrategy catchStrategy;
    private final BugProcessor bugProcessor;
    private Spider spider;
    private ExecutorService executor = Executors.newCachedThreadPool();

    private Runnable wordFullCallback;
    private Runnable exampleCallback;

    // TODO 如果是分布式, 可以把以下map功能, 弄到redis里
    private final ConcurrentHashMap<String, Long> catchIngMap = new ConcurrentHashMap();
    private volatile ConcurrentLinkedQueue<String> isDone = new ConcurrentLinkedQueue();
    private final ConcurrentHashMap<String, WordInfo> wordInfoMap = new ConcurrentHashMap();

    public void setWordFullCallback(Runnable wordFullCallback) {
        this.wordFullCallback = wordFullCallback;
    }

//    public void setExampleCallback(Runnable exampleCallback) {
//        this.exampleCallback = exampleCallback;
//    }

    public WordInfo pollIsDoneWord() {
        String word = isDone.poll();
        if(Strings.isEmpty(word)) { return null; }
        return wordInfoMap.remove(word);
    }

    public WordInfoManage(CatchStrategy catchStrategy) {
        this.catchStrategy = catchStrategy;
        this.catchStrategy.setWordInfoManage(this);
        this.bugProcessor = new BugProcessor(this, catchStrategy);
        this.spider = Spider.create(this.bugProcessor).setDownloader(new MyHttpClientDownloader()).thread(THREAD_COUNT);
        this.spider.setExitWhenComplete(false);
        this.spider.runAsync();;
//        new Thread(() -> {
//            spider.run();
//        }).start();
//        while (spider.getStatus().equals(Spider.Status.Init)) { }
    }

    public Spider getSpider() {
        return spider;
    }

    public WordInfo getWordInfo(String word) {
        return wordInfoMap.get(word);
    }

    // 是否这个单词正在被捕捉中
    public boolean hasWordIsCatching(String word) {
        return false;
    }

    public void catchWord(String word) {
        if(!catchIngMap.containsKey(word)) {
            synchronized (this) {
                if(catchIngMap.containsKey(word)) {
                    return;
                }
            }
            WordInfo wordInfo = new WordInfo();
            wordInfo.setWord(word);
            wordInfoMap.put(word, wordInfo);
            catchIngMap.put(word, System.currentTimeMillis());
            bugProcessor.catchWord(word);
        }
    }


    public boolean isFull(String word) {
        WordInfo wordInfo = wordInfoMap.get(word);
        if(wordInfo == null) {
            log.warn("word {} not found {}", word, WordInfo.class.getSimpleName());
            return false;
        }
        // 有可能某些数据网站上是没有的.
        if(
            wordInfo.getExplained() != null &&
            wordInfo.getUnderstand() != null &&
            wordInfo.getDetails() != null &&
            wordInfo.getAppear() != null
        ){ return true; }
        return false;
    }

    public void fullCallBack(String word) {
        long start = catchIngMap.get(word);
        System.out.println(word + "用时 " + (System.currentTimeMillis() - start));
        isDone.add(word);
        executor.execute(wordFullCallback);
        catchIngMap.remove(word);
        //wordInfoMap.remove(word);
    }

    public void exampleCatchDome() {
        executor.execute(exampleCallback);
    }

}
